# for whatever reason, this function needs to be in a different python file from where it's called to get
# the scope correct.
import datetime
import logging

from model import ImageUrlMap
from google.appengine.ext import deferred   #  WARNING: if you change anything in this file while the development
                                            # server is running, you will get a "cannot import name deferred" error.
                                            # Restarting the server will clear this.


# Delete all records after the starting time in batches of 1000
# Note: we use the start time as a marker. New images can be uploaded while old ones are being deleted.
def DeleteAllData(starttime=datetime.datetime.now()):
    q = ImageUrlMap.all()
    q.filter("datecreated <=", starttime)
    q.order("-datecreated")

    count = 0
    for r in q.fetch(1000):
        r.DeepDelete()
        count +=1
    logging.info("Bulk deleted %d records" % count)
    if count:
        deferred.defer(DeleteAllData, starttime=starttime,_countdown=1)


def DeleteBatchIDData(batchidstr, starttime=datetime.datetime.now()):
    q = ImageUrlMap.all()
    q.filter("batchid =", int(batchidstr))
    q.filter("datecreated <=", starttime)
    q.order("-datecreated")

    count = 0
    for r in q.fetch(1000):
        r.DeepDelete()
        count +=1
    logging.info("Bulk batchid=%s. Deleted %d records" % (batchidstr,count))
    if count:
        deferred.defer(DeleteBatchIDData, batchidstr=batchidstr, starttime=starttime,_countdown=1)

